<?php
class Registration_AuthController  extends Zendvn_Controller_Action{
	
	public function init(){
		parent::init();
		$this->view->main = TRUE;
		$this->view->module = "landpage";
	}
	
	
	public function loginAction()
    {
    	if($this->getRequest()->isPost()){
            //if($form->isValid($_POST)){
                //$data = $form->getValues();

        		if ($_POST['email'] && $_POST['password']){

        			if ($this->login($_POST['email'],$_POST['password'])){
        				
        				$this->_redirect('/');
        			}
        		
        		
        		}
        		       
            //}
               
        }
        
    } 
    public function signupAction()
    {
    $users = new Registration_Model_Auth();
        //$form = new Registration_Form_RegistrationForm();
        //$this->view->form=$form;
        if($this->getRequest()->isPost()){  	

        		$fullname = @$_POST['fullname'];
        		
        		$email = @$_POST['email'];
        		
        		$password = @$_POST['fullname'];
        	
        		if($fullname == ""){
                	$this->view->errorMessage = "Tên không được để trống.";                	
                    $this->_redirect('/registration/auth/login');
                }
            	if($email == ""){
                	$this->view->errorMessage = "Email không được để trống.";
                    $this->_redirect('/registration/auth/login');
                }
                if($password == ""){
                	$this->view->errorMessage = "Password không được để trống.";
                    $this->_redirect('/registration/auth/login');
                }                

                if (filter_var($email, FILTER_VALIDATE_EMAIL) == False) {
                	$this->_redirect('/registration/auth/login');
                }
                
                if ($users->checkUnique($email)){
                	$this->_redirect('/registration/auth/login');
                }
                
                $password = hash('sha256',"-".'!@#taha'."-".$_POST['password']."-");                
				$arrParam['displayname'] 	= $_POST['fullname'];
				$arrParam['email'] 	= $_POST['email'];
				$arrParam['password'] 		=  $password;								
				$userid = $users->insertUser($arrParam);
				
				
				
				
				if($arrParam['email'] && $arrParam['displayname']){
					$this->sendEmail($email, $fullname);
				}
				
				
				
				if($this->login($_POST['email'],$_POST['password'])){
					
					$this->_redirect('/registration/');
				}
				
                


        }
    } 
    public function logoutAction()
    {
    	$storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        
        $auth = new Registration_Model_Auth();
        
        $auth->removeAccountCookie();
        
        $this->_redirect('/');
    }
    public function homeAction()
    {
    	$storage = new Zend_Auth_Storage_Session();
        $data = $storage->read();
        
        if(!$data){
            $this->_redirect('/registration/auth/login');
        }
        
        $this->view->email = $data->email; 
    }
    
    public function login($email,$password){
    	
    		$users = new Registration_Model_Auth();
    		
    		$password = hash('sha256',"-".'!@#taha'."-".$_POST['password']."-");
        			
	        $auth = Zend_Auth::getInstance();
            $authAdapter = new Zend_Auth_Adapter_DbTable($users->getAdapter(),'user');
	        $authAdapter->setIdentityColumn('email')
	                    ->setCredentialColumn('password');
	        $authAdapter->setIdentity($email)
	                    ->setCredential($password);
	        $result = $auth->authenticate($authAdapter);
	                
            if($result->isValid()){
                
              	$storage = new Zend_Auth_Storage_Session();                    
              	$storage->write($authAdapter->getResultRowObject());
              	$session = new Zend_Session_Namespace('Zend_Auth');
				// Set the time of user logged in
				$session->setExpirationSeconds(24*3600);
				
				Zend_Session::rememberMe();
				
				$data = $storage->read();
				
				//Remember me
				$this->rememberMe($data);
				
				//Update time last login
				
				$arr = array(
				"id"=>$data->id,					
				"time_last_login"=>date('Y-m-d h:i:s',time()),				
				);
				
				$users->updateProfile($arr);
				
              	
				return TRUE;
              	
            } else {
              	$this->view->errorMessage = "Invalid username or password. Please try again.";
              	return FALSE;
            }
                	
    }
    
    public function updateprofileAction(){
    	$this->view->main = FALSE;
    	if($this->getRequest()->isPost()){    
    		$storage = new Zend_Auth_Storage_Session();
			$data = $storage->read();		  
    		$arrParam['id'] 		=  $data->id;  		
    		$arrParam['company'] 	= @$_POST["company"];
			$arrParam['school'] 	= @$_POST["school"];
			$arrParam['home'] 		= @$_POST["home"];
			
			$auth = new Registration_Model_Auth();
			$auth->updateProfile($arrParam);			
    		
    	}
    }
    
    public function uploadavatarAction(){
    	
    	$this->view->main = FALSE;
    	
    	if($this->getRequest()->isPost()){ 
    		
    		$storage = new Zend_Auth_Storage_Session();
			$data = $storage->read();
    		$user = new Registration_Model_Auth();
			$upload = new Zend_File_Transfer_Adapter_Http();
			
			$path = realpath(APPLICATION_PATH."/../upload/");
			
			$upload->setDestination($path);
			
			 $file = $upload->getFileInfo();
			 
			  $file_name = $upload->getFilename();
			  
			  preg_match("/\.([^\.]+)$/", $file_name, $matches); 
	          $file_ext = $matches[1];
	          $file_name = time() . '.' . $file_ext;
	          $upload->addFilter('Rename', $path .'/' . $file_name);
			
			if (!$upload->isValid()) 
			{
			    throw new Exception('Bad image data: '.implode(',', $upload->getMessages()));
			}
			
			try {
				
		        $upload->receive();
		        
		        $arr = array(
				"id"=>$data->id,					
				"avatar"=>$file_name,				
				);

				$data->avatar = $file_name;
				
				$user->updateProfile($arr);
				
				echo $file_name;
			        
			} 
			catch (Zend_File_Transfer_Exception $e) 
			{
			        throw new Exception('Bad image data: '.$e->getMessage());
			}
			
    		
    	}
    	
    }
    
	public function uploadlogoAction(){
    	
		
    	$this->view->main = FALSE;
    	
    	
    	
    	if($this->getRequest()->isPost()){ 
    		
    		$storage = new Zend_Auth_Storage_Session();
			$data = $storage->read();
    		$chanel = new Registration_Model_Chanel();
			$upload = new Zend_File_Transfer_Adapter_Http();
			
			$path = realpath(APPLICATION_PATH."/../upload/");
			
			$upload->setDestination($path);
			
			 $file = $upload->getFileInfo();
			 
			  $file_name = $upload->getFilename();
			  
			  preg_match("/\.([^\.]+)$/", $file_name, $matches); 
	          $file_ext = $matches[1];
	          $file_name = time() . '.' . $file_ext;
	          $upload->addFilter('Rename', $path .'/' . $file_name);
			
			if (!$upload->isValid()) 
			{
			    throw new Exception('Bad image data: '.implode(',', $upload->getMessages()));
			}
			
			try {
				
		        $upload->receive();
		        
		        $arr = array(
					"userid"=>$data->id,					
					"logo"=>$file_name,			
		        	"name"=>"",
		        	"create_date"=>"",
		        	"type"=>"",
		        	"location"=>"",
		        	"description"=>"",
		        	"cover"=>"",
				);
				
				
				$id = $chanel->insertChanel($arr);
				
				echo '{"id":"'.$id.'","img":"'.$file_name.'"}' ;
			        
			} 
			catch (Zend_File_Transfer_Exception $e) 
			{
			        throw new Exception('Bad image data: '.$e->getMessage());
			}
			
    		
    	}
    	
    }
    
	public function sendEmail($user_email, $name) {

		$email = new Email_Model_Index();
		
		$transport = $email->connectSmtp();
        
        // create view object
		$html = new Zend_View();
		$html->setScriptPath(APPLICATION_PATH . '/modules/registration/views/scripts/mail/');
		
		//channels
		
		$chanel = new Chanel_Model_Index();		
		
		$page = 1;
		
		$pagesize = 10;
		
		$arr = array(	
			"userid"=>"",			
			"page"=> $page,
			"pagesize"=> $pagesize,
																
		);
		
		$list_chanel = $chanel->listItem($arr);
		
		
		// assign valeues
		$html->assign('name', $name);
		$html->assign('list_chanel', $list_chanel);
			
		$mail = new Zend_Mail('utf-8');
		
		// render view
		$bodyText = $html->render('signup.phtml');
		
		$mail->setFrom('channel@otaha.com', 'Otaha');
		$mail->addTo($user_email);
		$mail->setSubject('Chào mừng đến với Otaha');
		$mail->setBodyHtml($bodyText);	
		
		$mail->send($transport);
		
		
    } 

    public function rememberMe($user){    	
    	
    	$request = new Zend_Controller_Request_Http();
  		$u = $request->getCookie("uotaha");
  		$p = $request->getCookie("potaha");
  		
  		$auth = new Registration_Model_Auth();    	
    	$name_username  = "uotaha";    	
    	$name_password  = "potaha";
  		
  		if (!isset($u)){

  			$username = $auth->encrypt($user->email);
  			setcookie("uotaha", $username, time()+86400 * 365 * 2);
  			
  		}
    	if (!isset($p)){

  			$password = $auth->encrypt($user->password);
  			setcookie("potaha", $password, time()+86400 * 365 * 2);
  			
  		}
    	    	
    }
    
    
	
}